// pages/file/detail.js
const app = getApp()
var util = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgarr:[],
    form_data:{public_id:0,price:0,token:wx.getStorageSync('token')},
    id: '',
    info: {},
    isMask: false,
    isPay: false,
    isSuccess: false,
    minprice: 30,
    payprice: 0,
    type: 0,
    filepath: '', //支付后下载链接
  },
  getData(id) {
    let that = this;
    let res = {
      title: '',
      date: ' ',
      payStatus: 0,//0-未付费，1-已付费
      filename: '跃迁：成为高手的技术.pdf',
      filesize: '1.1MB',
      filepath: '',
      divHtml: ''
    }
    //富文本
    that.setData({
      info: res
    })
  },
  //解锁
  onUnlock(e) {
    if(this.data.info.payStatus == 0){
      this.setData({
        isMask: true,
        isPay: true
      })
    }else{
      this.setData({
        type: 1
      })
    }
  },

  //关闭支付弹窗
  onCloseMask() {
    this.setData({
      isMask: false,
      isPay: false,
      isSuccess: false,
      payprice: 0
    })
  },

  //监听金额输入
  priceinput(e) {
    let value = e.detail.value;
    this.setData({
      payprice: parseFloat(value),
      'form_data.public_id':this.data.info.id,
      'form_data.price':this.data.payprice,
      'form_data.token':this.data.form_data.token
    })
  },
  //支付
  onPay() {
    let payprice = this.data.payprice;
    let that=this
    console.log(payprice)
    //调取支付接口
    app.curl(util.web_url.recharge_pay2,that.data.form_data,'POST',false,false,this,getCurrentPages()).then( (res)=>{
    
      console.log(res.data)
    wx.requestPayment({
      timeStamp: res.data.timeStamp,
      nonceStr: res.data.nonceStr,
      package: res.data.package,
      signType: 'MD5',
      paySign: res.data.paySign,
      success (ress) {console.log(ress) 
        console.log(ress)
        //util.msg('充值成功')
        
        that.setData({
          isPay: false,
          payprice: 0,
          isSuccess: true,
          'info.payStatus':true
        })
  
      },
      fail (ress) { }
    })
  }).catch( (errMsg)=>{});
 
  },
  onSeeFile(){
    this.setData({
      ['info.payStatus']: 1
    })
    this.onCloseMask();
  },getFilePathName(path) {
    let pos1 = path.lastIndexOf('/');
    let pos2 = path.lastIndexOf('\\');
    let position  = Math.max(pos1, pos2);
    if ( position< 0 )
      return path;
    else
      return path.substring(position+ 1);
    },catchImage(e){
      console.log(e)
    
        console.log(this.data.imgarr);
        wx.previewImage({
          current: this.data.imgarr[0], // 当前显示图片的http链接
          urls: this.data.imgarr // 需要预览的图片http链接列表
        })
      },
  //下载
  onDownFile2() {
    var that =this
    let file = (that.data.info.filepath);
    
    console.log(file)
    util.msg('正在加载文档中,请等待')
    console.log(that.data.info.fileType)
    wx.downloadFile({ //下载
      url: file, //服务器上的pdf地址
     
      success: function (res) {
        console.log(res)
        const fileManager = wx.getFileSystemManager();
        fileManager.saveFile({
          tempFilePath: res.tempFilePath,
          success: (res) => {
          
            let arr = ["jpg","gif","png","jpeg"];

           var res1234 = arr.indexOf(that.data.info.fileType)
           console.log(res1234)
           if(res1234 > -1){
            that.setData({imageUrl:res.savedFilePath})
             console.log(res)
            wx.previewImage({
              current: that.data.info.filepath,
              urls: [that.data.info.filepath] // 需要预览的图片http链接列表
            })
           }else{
            util.msg('加载成功,等待打开文档后分享')
            setTimeout(function(){
              wx.openDocument({
                filePath: res.savedFilePath,
                fileType:that.data.info.fileType,
                showMenu: true,
              })
            },1000)
           }
         
         
       
          }
        })

      }
    })
  },  onDownFile() {
    var that =this
    let file = (that.data.info.filepath);
    
    console.log(file)
    util.msg('正在加载文档中,请等待')
    console.log(that.data.info.fileType)
    const flieArr = that.data.info.filepath.split('/')
    const filename = flieArr[flieArr.length - 1]
    wx.downloadFile({ //下载
      url: file, //服务器上的pdf地址
      filePath:wx.env.USER_DATA_PATH+'/'+filename,
      success: function (res) {
        console.log(res)
        const fileManager = wx.getFileSystemManager();

          let arr = ["jpg","gif","png","jpeg"];
           var res1234 = arr.indexOf(that.data.info.fileType)
           console.log(res1234)
           if(res1234 > -1){
            that.setData({imageUrl:res.savedFilePath})
             console.log(res)
            wx.previewImage({
              current: that.data.info.filepath,
              urls: [that.data.info.filepath] // 需要预览的图片http链接列表
            })
           }else{
            util.msg('加载成功,等待打开文档后分享')
            setTimeout(function(){
              wx.openDocument({
                filePath: res.filePath,
                fileType:that.data.info.fileType,
                showMenu: true,
              })
            },1000)
           }
         
         
       
          }
      
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    util.check_login()
    let that = this
    wx.login({
      success (res) {
        if (res.code) {
          //发起网络请求
          wx.request({
            url: util.web_url.get_openid,
            data: {
              code: res.code
            },
            success: function (res) {
              console.log(res.data.openid)
                that.setData({'form_data.openid':res.data.openid})
                    }
            
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
    let id = options.id;
    this.getData(id);
    app.curl(util.web_url.public_view_manage,{id:id,token:wx.getStorageSync('token')},'GET',false,false,this,getCurrentPages()).then( (res)=>{
                  // 主要代码
let imgarr = [];
let regex = new RegExp(/<img.*?(?:>|\/>)/gi); // 匹配所有图片
let srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i; // 匹配src图片
let arrsImg = res.data.content.match(regex) ?? 0;; // obj.info 后台返回的富文本数据
console.log(arrsImg)
for (let a = 0; a < arrsImg.length; a++) {
    let srcs = arrsImg[a].match(srcReg);
    imgarr.push(srcs[1])
}
      this.setData({'info.title':res.data.title,'info.divHtml':res.data.content,'info.data':res.data.data,'info.height':res.data.height,'info.payStatus':res.data.payStatus,'info.price':res.data.price,'info.date':res.data.date,'info.filepath':res.data.filepath,'info.id':res.data.id,'info.filesize':res.data.size,minprice:res.data.price,'info.fujian':res.data.fujian,'info.fileType':res.data.fileType,imgarr:imgarr})
  })
},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(e) {
console.log(e)
    return {title:this.data.info.title,path:'pages/file/detail?id='+this.info.id,imageUrl:'/images/logn.png'};
  }
})